<?php

    namespace Wulian\Controller;
    use Common\Controller\HomebaseController;
    /**
     * 微信端
     */
    class IndexController extends HomebaseController {

        public $m_card,$m_package,$m_order,$m_cron;
        function _initialize() {
            parent::_initialize();
            $this->m_card= D("Wulian/WlCard");
            $this->m_package = M("WlPackage");
            $this->m_order = M("WlOrder");
            $this->m_cron = M("WlCron");
        }


        //首页
        public function index() {
            $card_iccid = I("card_iccid");
            if(empty($card_iccid)){
                $card_iccid = session("card_iccid");
            }
            if(!empty($card_iccid)){
                $card = $this->m_card->where(array("card_iccid"=>$card_iccid))->find();
                $card_number = $card["card_number"];
                $this->assign("card", $card);
                if(empty($card_number)){
                    echo "<script>alert('您输入的卡号有误，请检查后重新输入');</script>";
                }else{
                    $telecom = new \Wulian\Lib\telecom();
                    $telecom->poolNbr = $this->wl_config['flow_pool_id'];
                    $data = $telecom->getPoolMemQry(1,$card_number);
                    if(isset($data["PoolInfo"])){
                        $plus_flow = ($card["package_data_month"]+$card["package_data_add"])*1024-($data["PoolInfo"]["POOL_MEMBER_ALREADY"]*$this->wl_proportion);
                        $plus_flow = kbToM($plus_flow);
                        $this->assign("plus_flow", $plus_flow);
                    }else{
                        echo "<script>alert('{$data['Response']['RspDesc']}');</script>";
                    }
                    session("card_iccid",$card_iccid);
                }

            }else{
                $card_iccid = $this->wl_config["h5_prefix"];
            }
            $this->assign("card_iccid", $card_iccid);
            $this->display();
        }

        /**
         * 充值
         */
        public function recharge(){
            $url = U('index/index');
            $card_iccid = I("card_iccid");
            if(empty($card_iccid)){
                $card_iccid = session("card_iccid");
            }else{
                session("card_iccid",$card_iccid);
            }

            if(empty($card_iccid)){
                echo "<script>alert('请输入卡号');location.href='{$url}'</script>";exit;
            }else{
                $this->assign("card_iccid", $card_iccid);
                //查询该卡当前使用的套餐
                $card = $this->m_card->where(array("card_iccid"=>$card_iccid))->find();
                if(!$card){
                    echo "<script>location.href='{$url}'</script>";exit;
                }
                $card["package_data_month"] = mToG($card["package_data_month"]);
                if(!empty($card["package_data_add"])){
                    $card["package_data_add"] = mToG($card["package_data_add"]);
                }

                $this->assign("card", $card);

                //获取用户当前使用的月套餐
                $last_package = $this->m_package->where(array("package_id"=>$card["package_id_month"]))->find();
                if(!$last_package){
                    echo "<script>alert('当前卡尚未关联套餐，请联系客服解决');location.href='{$url}'</script>";exit;
                }

                //获取开启中的月套餐列表
                $month_list = $this->m_package->where(array("is_del"=>0,"package_type"=>1,'package_status'=>1))->order("sort")->select();
                foreach($month_list AS &$mitem){
                    if($last_package['package_data']<$mitem['package_data']){
                        $p_month = getPlusMonth($card['package_endtime']);
                        //获取月套餐的价格差值
                        $mitem['pay_price'] = max(0,($mitem['package_price']-$last_package['package_price'])*($p_month+1));
                    }else{
                        $mitem["pay_price"] = 0;
                    }
                }

                $add_list = $this->m_package->where(array("is_del"=>0,"package_type"=>2,'package_status'=>1))->order("sort")->select();
                foreach($add_list AS &$aitem){
                    $aitem["package_title_data"] = mToG($aitem["package_data"]);
                    $aitem["pay_price"] = $aitem["package_price"];
                }

                //获取年续费的套餐
                $last_package["pay_price"] = $last_package["package_price"]*12;

                $this->assign("year_package", $last_package);
                $this->assign("month_list", $month_list);
                $this->assign("add_list", $add_list);
            }
            $this->display();
        }

        /**
         * 支付
         */
        public function pay(){
            $url = U('index/index');
            $url_recharge = U('index/recharge');
            $card_iccid = session("card_iccid");
            if(empty($card_iccid)){
                echo "<script>alert('请输入卡号');location.href='{$url}'</script>";exit;
            }
            $package_id = I("package_id");
            $is_year = isset($_GET['is_year'])?I("is_year"):0;
            $card = $this->m_card->where(array("card_iccid"=>$card_iccid))->find();
            if(!$card){
                echo "<script>alert('您输入的卡号有误，请检查后重新输入');location.href='{$url}'</script>";exit;
            }elseif(!$is_year && time()>=$card['package_endtime']){
                echo "<script>alert('您的月套餐已过期，请先购买年套餐续费!');location.href='{$url_recharge}'</script>";exit;
            }
            $package = $this->m_package->where(array("package_id"=>$package_id,'is_del'=>0))->find();
            if(empty($package)){
                echo "<script>alert('该套餐已经删除！');location.href='{$url}'</script>";exit;
            }
            if($is_year){   //年续费
                $price = $package["package_price"]*12;
            }else{
                if($package["package_status"]==0){
                    echo "<script>alert('该套餐已经关闭！');location.href='{$url}'</script>";exit;
                }
                if($package["package_type"] == 1){      //月套餐
                    $last_package = $this->m_package->where(array("package_type"=>1,"package_id"=>$card["package_id_month"]))->find();
                    if($last_package['package_data']<$package['package_data']){
                        $p_month = getPlusMonth($card['package_endtime']);
                        $price = ($package['package_price']-$last_package['package_price'])*($p_month+1);
                    }else{
                        $price = 0;
                    }
                }else{
                    $price = $package["package_price"];
                }

            }
            if($price == 0){
                $order_number = date("YmdHis").rand(100000,999999);
                $result = addOrder($this->wl_config["flow_pool_id"],$card["card_number"],$package_id,0,$order_number,"",2,$is_year);
                if(!$result){
                    echo "<script>alert('充值失败，请重新操作');location.href='{$url_recharge}'</script>";exit;
                }
                $order = $this->m_order->where(array("order_number"=>$order_number,'order_status'=>0))->find();

                $telecom = new \Wulian\Lib\telecom();
                $telecom->poolNbr = $this->wl_config['flow_pool_id'];
                if($order["package_type"] == 1 || $order["package_type"] == 3){ //月套餐 或者 年续费
                    $new_packe_data = $card["package_data_add"]+$order["package_data"];
                }else{  //增量包
                    $new_packe_data = $card["package_data_month"]+$card["package_data_add"]+$order["package_data"];
                }

                $package_data = round($new_packe_data/$this->wl_config["proportion"],0);
                $result = $telecom->modifyPoolMember($order["card_number"],(int)$package_data);
                if($result["Response"]["RspCode"] == '0000'){
                    successOrder($order_number,date('YmdHis').rand(1000,9999));
                    echo "<script>alert('购买成功!');location.href='{$url}'</script>";exit;
                }else{
                    echo "<script>alert('购买失败!');location.href='{$url}'</script>";exit;
                }

            }else{
                $order_number = date("YmdHis").rand(100000,999999);
                $result = wx_pay("上海裔剑物联系统",$order_number,$price*100);

                $jsApiParameters = $result["jsApiParameters"];
                $openid = $result["openid"];

                $result = addOrder($this->wl_config["flow_pool_id"],$card["card_number"],$package_id,0,$order_number,$openid,2,$is_year,$price);
                if(!$result){
                    echo "<script>alert('充值失败，请重新操作');location.href='{$url_recharge}'</script>";exit;
                }

                $this->assign("jsApiParameters", $jsApiParameters);
                $this->assign("price", $price);
                $this->assign("order_number", $order_number);
                $this->display();
            }

        }

        /**
         * 回调
         */
        public function notify(){
            $price = I("post.price");
            $order_number = I("post.order_number");
            $transaction_id = I('post.transaction_id');
            $order = $this->m_order->where(array("order_number"=>$order_number,'order_status'=>0))->find();
            $card = $this->m_card->where(array("card_number"=>$order["card_number"]))->find();
            if(round($order["order_price"],2) == round($price,2)){

                $telecom = new \Wulian\Lib\telecom();
                $telecom->poolNbr = $this->wl_config['flow_pool_id'];
                if($order["package_type"] == 1 || $order["package_type"] == 3){ //月套餐 或者 年续费
                    $new_packe_data = $card["package_data_add"]+$order["package_data"];
                }else{  //增量包
                    $new_packe_data = $card["package_data_month"]+$card["package_data_add"]+$order["package_data"];
                }

                $package_data = round($new_packe_data/$this->wl_config["proportion"],0);
                $result = $telecom->modifyPoolMember($order["card_number"],(int)$package_data);
                if($result["Response"]["RspCode"] == '0000'){
                    successOrder($order_number,$transaction_id);
                    return true;
                }else{
                    //这里的含义其实是  失败的充值操作 月套餐 增量包 年续费
                    $cron = $this->m_cron->where(array("order_id"=>$order["order_id"]))->find();
                    if(empty($cron)){
                        $cron_insert = array(
                            "cron_type"=>2,
                            "package_data"=>$order["package_data"],
                            "order_id"=>$order["order_id"],
                            "cron_plus"=>2,
                            "cron_endtime"=>time(),
                            'transaction_id'=>$transaction_id
                        );
                        $this->m_cron->add($cron_insert);
                    }
                    return false;
                }
            }else{
                return false;
            }

        }


    }


